package com.mxx.common.netty.http.resolvers;

import com.fasterxml.jackson.databind.JavaType;
import com.mxx.common.conv.JacksonConverter;
import com.mxx.common.netty.annotation.Json;
import com.mxx.common.netty.http.NettyHttpRequest;
import com.mxx.common.netty.http.NettyMethod;
import com.mxx.common.netty.http.NettyMethodParameter;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Auther: Mr. Zeng
 * @Date: 2020/8/4 11:18
 * @Description: 暂无描述
 */

@Component
public class JsonParameterResolvers extends AbstractNettyResolvers {
    public JsonParameterResolvers(JacksonConverter jacksonConverter) {
        super(jacksonConverter);
    }

    @Override
    public boolean match(NettyMethod nettyMethod, NettyMethodParameter methodParameter) {
        if (methodParameter.getAnnotation(Json.class) == null) {
            return false;
        }
        flashParamType(nettyMethod, methodParameter);
        return true;
    }

    @Override
    public Object resolvers(NettyMethod nettyMethod, NettyHttpRequest request, NettyMethodParameter methodParameter) throws IOException {
        Json json = methodParameter.getAnnotation(Json.class);
        String paramName;
        if (json.value().isEmpty()) {
            paramName = methodParameter.getName();
        } else {
            paramName = json.value();
        }
        Object val = request.getJsonBody(paramName);
        JavaType javaType = getJavaType(nettyMethod, methodParameter);
        return jacksonConverter.convertValue(val,javaType);
    }
}
